package com.example.demo.service.impl;

import com.example.demo.entity.Goods;
import com.example.demo.entity.User;
import com.example.demo.mapper.GoodsMapper;
import com.example.demo.service.GoodsService;

import com.example.demo.service.MiddleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author chenhuiyu
 * @Date 2023/12/1
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    private static final Logger log = LoggerFactory.getLogger(GoodsServiceImpl.class);
    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Long addGoods(Goods goods) {
        Goods good = goodsMapper.findGoodsByUserIdAndName(goods.getUserId(), goods.getName());
        if (good != null) {
            return 0L;
        }
        Date date = new Date(System.currentTimeMillis());
        goods.setCreateTime(date);
        goods.setUpdateTime(date);
        Long l = goodsMapper.insertGoods(goods);
        log.debug("插入goods数据{}", l);
        return l;
    }

    @Override
    public Long updateGoods(User user) {

        List<Goods> goods = goodsMapper.findGoodsByUserId(user.getId());
        List<Goods> goodsList = new ArrayList<>();
        for (Goods good : goods) {
            if (good.getFlag() == 0) {
                good.setFlag(1);
                goodsList.add(good);
            }
        }
        Long id = goodsMapper.updateGoodsById(goodsList);
        log.debug("更新id为{}的goods数据", id);
        return id;
    }

    @Override
    public Map<String, Goods> findGoods(User user) {
        //
        Map<String, Goods> map;
        if (user != null && user.getId() != null) {
            map = goodsMapper.findGoods(user.getId());
        } else {
            map = null;
        }
        log.debug("findGoods获取{}条goodsMap数据", map == null ? 0 : map.size());
        return map;
    }

    @Override
    public List<Goods> findGoodsListByGroupId(Integer groupId) {
        List<Goods> goodsList = goodsMapper.findGoodsListByGroupId(groupId);
        log.debug("findGoodsByIdGroupId获取{}条goods数据", goodsList.size());
        return goodsList;
    }

    @Override
    public List<Goods> findGoodsByIdList(List<Integer> goodsIdList) {
        List<Goods> goodsList = goodsMapper.findGoodsByIdList(goodsIdList);
        log.debug("findGoodsByIdList获取{}条goods数据", goodsList.size());
        return goodsList;
    }

    @Override
    public List<Goods> findGoodsList(Goods goods) {
        List<Goods> goodsList = goodsMapper.findGoodsList(goods);
        log.debug("findGoodsList获取{}条goods数据", goodsList.size());
        return goodsList;
    }
}
